package com.example.cadmin.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.entity.Archives;
import com.example.cadmin.entity.BorrowingRecords;
import com.example.cadmin.entity.Host;
import com.example.cadmin.log.FileLogInsert;
import com.example.cadmin.mapper.ArchivesMapper;
import com.example.cadmin.mapper.BorrowingRecordsMapper;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WebApiService {

    @Resource
    public ArchivesMapper archivesMapper;
    @Resource
    public BorrowingRecordsMapper borrowingRecordsMapper;
    @Resource
    public HostService hostService;
    @Resource
    public com.example.cadmin.utils.Netty.sendCmd sendCmd;

    /**
     * 档案列表接口
     */
    public Map<String, Object> archivesList(int page, int limit, String fileName, String number, String layer, String column,
                                            String userName, String startDate, String endDate, String year, String reference, String fileId,
                                            String fileNo) {
        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isNotEmpty(fileName)) {
            paramsMap.put("file_name", fileName);
        }
        if (StrUtil.isNotEmpty(layer)) {
            paramsMap.put("current_layer", layer);
        }
        if (StrUtil.isNotEmpty(column)) {
            paramsMap.put("current_column", column);
        }
        if (StrUtil.isNotEmpty(number)) {
            paramsMap.put("number", number);
        }
        if (StrUtil.isNotEmpty(year)) {
            paramsMap.put("year", year);
        }
        if (StrUtil.isNotEmpty(startDate) && StrUtil.isNotEmpty(endDate)) {
            // 时间偏于一天
            Date date = DateUtil.parse(endDate, "yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String formatDate = DateUtil.formatDate(newDate);
            paramsMap.put("startTime", startDate);
            paramsMap.put("endTime", formatDate);
        }
        if (StrUtil.isNotEmpty(userName)) {
            paramsMap.put("user_name", userName);
        }
        if (StrUtil.isNotEmpty(reference)) {
            paramsMap.put("reference", reference);
        }
        if (StrUtil.isNotEmpty(fileId)) {
            paramsMap.put("file_id", fileId);
        }
        if (StrUtil.isNotEmpty(fileNo)) {
            paramsMap.put("file_no", fileNo);
        }
        List<Map<String, Object>> mapList = archivesMapper.archivesList(paramsMap);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("code", 0);
        resMap.put("msg", "数据请求成功");
        resMap.put("data", mapList);
        resMap.put("count", archivesMapper.archivesListCount(paramsMap));
        return resMap;
    }

    /**
     * 取出档案保存
     */
    public ResponseModel takeOutSave(JSONObject data, HttpServletRequest request) {
        // 老版本
        Archives archives = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_name", data.getStr("fileName")));
        archives.setStatus(1);
        archivesMapper.updateById(archives);
        FileLogInsert.insert("档案管理", "取出" + data.getStr("fileName") + "档案", 4, archives.getNumber(),data.getStr("fileName"));
        //添加借阅记录
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileName(data.getStr("fileName"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(1);
        borrowingRecords.setStatus(1);
        borrowingRecords.setNumber(archives.getNumber());
        int state = borrowingRecordsMapper.insert(borrowingRecords);
        //发送取档命令
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", archives.getNumber()));

        sendCmd.send("TCPTAKEOUT:" + archives.getCurrentLayer() + "/" + archives.getCurrentColumn(), null, host.getIp());
        return state > 0 ? ResponseModel.success("取出档案名为  " + data.getStr("fileName") + "  成功") : ResponseModel.fail("取出档案提交失败");
    }


    /**
     * 归还档案
     */
    public ResponseModel returnFile(JSONObject data, HttpServletRequest request) {
        Archives archives = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_name", data.getStr("fileName")));
        archives.setStatus(0);
        //判断此次归还位置是否和之前一样
        if (!archives.getCurrentLayer().equals(data.getStr("layer"))) {
            archives.setCurrentLayer(data.getStr("layer"));
        }
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number",archives.getNumber()));


        int returnExists = archivesMapper.updateById(archives);
        FileLogInsert.insert("档案管理", "归还" + data.getStr("fileName") + "档案", 5, archives.getNumber(),data.getStr("fileName"));
        //添加借阅记录
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileName(data.getStr("fileName"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(2);
        borrowingRecords.setStatus(1);//层 和 列

//        borrowingRecords.setReturnLayer(data.getStr("layer"));
        borrowingRecords.setNumber(archives.getNumber());
        borrowingRecordsMapper.insert(borrowingRecords);
        //发送归档命令tcptakein：
            sendCmd.send("TCPTAKEIN:" + archives.getCurrentLayer() + "/" + archives.getCurrentColumn(), null, host.getIp());

        return returnExists > 0 ? ResponseModel.success("归还档案名  " + data.getStr("fileName") + "  成功") : ResponseModel.fail("归还档案失败");
    }

    /**
     * 借阅记录-借出档案-表格接口
     *
     * @param page
     * @param limit
     * @return
     */
    public Map<String, Object> recordsList(String fileName,String fileId,String number,String recordType, int page, int limit) {
        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isNotEmpty(fileName)) {
            paramsMap.put("fileName", fileName);
        }
        if (StrUtil.isNotEmpty(fileId)) {
            paramsMap.put("fileId", fileId);
        }
        if (StrUtil.isNotEmpty(number)) {
            paramsMap.put("number", number);
        }
        if (StrUtil.isNotEmpty(recordType)) {
            paramsMap.put("recordType", recordType);
        }
        List<Map<String, Object>> mapList = borrowingRecordsMapper.recordsList(paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("data", mapList);
        map.put("count", borrowingRecordsMapper.recordsListCount(paramsMap));
        return map;
    }
}
